package com.ruoyi.common.qy.utils;

import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class UrlExtractor {
    public static String douyinUrlExtractor(String url) {
//        String url = "https://v.douyin.com/lxRlw06mDaI/";

        // 方法1：使用正则表达式提取路径
        String pattern = "https://v\\.douyin\\.com/([^/]+)";
        java.util.regex.Pattern r = java.util.regex.Pattern.compile(pattern);
        java.util.regex.Matcher m = r.matcher(url);

        if (m.find()) {
            String result = m.group(1);
            System.out.println(result); // 输出: lxRlw06mDaI
            return result;
        }
        return null;
    }
    public static String getFileId(String urlString) {
        try {
            URL url = new URL(urlString);
            String query = url.getQuery();
            Map<String, String> queryParams = splitQuery(query);
            return queryParams.get("file_id");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Map<String, String> splitQuery(String query) throws Exception {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
            String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
            queryPairs.put(key, value);
        }
        return queryPairs;
    }

}
